
//Model 用于管理状态并触发通知
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class CounterNotifier with ChangeNotifier { //mixin
//class CounterNotifier extends ChangeNotifier {
  int _count = 0; //私有字段

  //提供只读属性
  int get count => _count;

  void increment() {
    _count++; //修改状态
    notifyListeners(); //手动触发更新，通知所有监听者
  }
}

class CounterNotifierStatefulWidget extends StatefulWidget {
  const CounterNotifierStatefulWidget({super.key});

  @override
  State<CounterNotifierStatefulWidget> createState() => _CounterNotifierStatefulWidgetState();
}

class _CounterNotifierStatefulWidgetState extends State<CounterNotifierStatefulWidget> {
  //
  final CounterNotifier _counterNotifier = CounterNotifier();

  @override
  void initState() {
    super.initState();
    _counterNotifier.addListener(() {
      print('addListener Callback');
      setState(() {}); //触发 UI 更新
    });
  }

  @override
  Widget build(BuildContext context) {
    print('build');
    return Scaffold(
      appBar: AppBar(
        title: const Text('ChangeNotifier 示例'),
      ),
      body: Center(
          child: Text(
            'count: ${_counterNotifier.count}',
          )),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _counterNotifier.increment(),
        child: const Icon(Icons.add),
      ),
    );
  }

  @override
  void dispose() {
    _counterNotifier.dispose();
    super.dispose();
  }
}


